/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package me.joshua.demo4j.spring.mvc.first;

import me.joshua.demo4j.spring.data.jpa.first.UserModel;
import me.joshua.demo4j.spring.data.jpa.first.UserRepository;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


/**
 *
 * @author Joshua
 */
@Controller
public class User {

	@Autowired
	private UserRepository userRepository;

	@RequestMapping(value = "/add/{name}", method = RequestMethod.GET)
	public String add(@PathVariable String name, Model model) {
		name = StringUtils.trimToNull(name);
		if (null == name) {
			model.addAttribute("error", "Empty name");
			return "/error";
		}

		UserModel user = new UserModel(name);
		try {
			userRepository.save(user);
		} catch (Exception e) {
			model.addAttribute("error",
					String.format("User[%s] insert error", user.getName()));
			return "/error";
		}

		model.addAttribute("user", user);
		return "/user/info";
	}

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Model model) {
		Iterable<UserModel> itr = userRepository.findAll();
		model.addAttribute("itr", itr);
		return "/user/list";
	}
}
